package com.quzhi.sys.controller.orderController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quzhi.common.Utils;
import com.quzhi.common.code.Code;
import com.quzhi.common.Result;
import com.quzhi.sys.entity.*;
import com.quzhi.sys.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.security.x509.SerialNumber;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 序列号控制器
 * </p>
 *
 * @author Xibing
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/sys/orderSerialNumber")
public class OrderSerialNumberController {
    @Autowired
    private OrderSerialNumberServiceImpl serialNumberService;


    @Autowired
    private GoodsSerialNumberServiceImpl goodsSerialNumberService;

    @Autowired
    private TransferRecordServiceImpl transferRecordService;

    @Autowired
    private OrderLogServiceImpl orderLogService;

    @Autowired
    private OrderServiceImpl orderService;


    @Autowired
    private UserServiceImpl userService;

    // 添加订单绑定序列号 订单序列号
    @PostMapping
    public Result<?> addSerialNumberOrder(@RequestBody OrderSerialNumber orderSerialNumber, HttpServletRequest request) {

        // 查询数据库是否有待出库的序列号和这个序列号一样的
        LambdaQueryWrapper<OrderSerialNumber> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderSerialNumber::getSerialNumber, orderSerialNumber.getSerialNumber());
        wrapper.eq(OrderSerialNumber::getStatus, Code.DAI_CHU_KU);
        List<OrderSerialNumber> list = serialNumberService.list(wrapper);


        String token = Utils.getToken(request);
        String username = userService.getUserinfoForBack(token).getUsername();

        if (list != null && list.size() > 0) {
            StringBuilder orderNumbers = new StringBuilder();
            for (OrderSerialNumber serialNumber : list) {
                // 查询序列号绑定的订单编号
                Order order = orderService.getById(serialNumber.getOrderId());
                orderNumbers.append(order.getOrderNumber()).append(" ");
            }
//
//            if (!orderNumbers.toString().equals("")) {
//                // 添加重复序列号日志
//                orderLogService.AddUserLog(orderSerialNumber.getOrderId(), orderSerialNumber.getSerialNumber() + "序列号重复，与" + orderNumbers + "的序列号重复", username);
//            }

            return Result.fail(Code.UPDATE_FAIL_CODE, orderSerialNumber.getSerialNumber() + "序列号重复，与" + orderNumbers + "的序列号重复，请先设置序列号出库");
        }

        // 设置ID
        orderSerialNumber.setId(UUID.randomUUID().toString());

        // (待出库)
        orderSerialNumber.setStatus(Code.DAI_CHU_KU);

        // 设置创建时间
        orderSerialNumber.setCreateTime(LocalDateTime.now());
        // 设置更新时间
        orderSerialNumber.setUpdateTime(LocalDateTime.now());


        serialNumberService.save(orderSerialNumber);

        return Result.success("新增序列号成功");
    }


    @PostMapping("/addSerialNumber")
    public Result<?> addSerialNumber(@RequestBody Map<String, Object> order, HttpServletRequest request) {

        String token = Utils.getToken(request);
        String username = userService.getUserinfoForBack(token).getUsername();

        String id = (String) order.get("id");
        // 先删除订单绑定的所有序列号
        LambdaQueryWrapper<OrderSerialNumber> orderSerialNumberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderSerialNumberLambdaQueryWrapper.eq(OrderSerialNumber::getOrderId, id);

        serialNumberService.remove(orderSerialNumberLambdaQueryWrapper);


        // 删除订单所有序列号重复日志
        LambdaQueryWrapper<OrderLog> osnWrapper = new LambdaQueryWrapper<>();
        osnWrapper.eq(OrderLog::getOrderId, id);
        osnWrapper.like(OrderLog::getLog, "序列号重复");
        orderLogService.remove(osnWrapper);


        // 获取传入的序列号
        String serialNumbers = (String) order.get("serialNumber");

        if (serialNumbers.trim().equals("")) {
            return Result.fail(Code.ADD_ORDER_FAIL, "请输入序列号");
        }


        // 更具要求格式，格式化序列号
        String[] serialNumber = serialNumbers.split("/");


        // 检测添加的序列号是否绑定订单

        for (String s : serialNumber) {
            OrderSerialNumber orderSerialNumber = new OrderSerialNumber();
            // 查询数据库是否有待出库的序列号和这个序列号一样的
            LambdaQueryWrapper<OrderSerialNumber> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderSerialNumber::getSerialNumber, s);
            wrapper.eq(OrderSerialNumber::getStatus, Code.DAI_CHU_KU);
            List<OrderSerialNumber> list = serialNumberService.list(wrapper);

            StringBuilder orderNumber = new StringBuilder();
            for (OrderSerialNumber number : list) {
                Order orderServiceById = orderService.getById(number.getOrderId());
                orderNumber.append(orderServiceById.getOrderNumber()).append(" ");

            }
            if (!orderNumber.toString().equals("")) {
                return Result.fail(Code.UPDATE_FAIL_CODE, s + "序列号重复，与" + orderNumber + "的序列号重复，请先设置序列号出库");
//                // 添加重复序列号日志
//                orderLogService.AddUserLog(id, s + "序列号重复，与" + orderNumber + "的序列号重复", username);
            }


            // 添加传入的序列号
            // 设置ID
            orderSerialNumber.setId(UUID.randomUUID().toString());

            // 设置默认状态(待出库)
            orderSerialNumber.setStatus(Code.DAI_CHU_KU);

            // 设置绑定的订单编号
            orderSerialNumber.setOrderId(id);

            // 设置序列号
            orderSerialNumber.setSerialNumber(s);

            // 设置创建时间
            orderSerialNumber.setCreateTime(LocalDateTime.now());
            // 设置更新时间
            orderSerialNumber.setUpdateTime(LocalDateTime.now());

            serialNumberService.save(orderSerialNumber);
        }

        // 更新日志
        orderLogService.AddSystemLog(id, "备货更新序列号：" + serialNumbers, userService.getUserinfoForBack(request.getHeader("qz-Token")).getUsername());
        return Result.success("添加成功");


    }


    /**
     * 序列号调拨
     *
     * @param transfer
     * @return
     */
    @PostMapping("/TransferSerialNumber")
    public Result<?> TransferSerialNumber(@RequestBody Map<String, Object> transfer, HttpServletRequest request) {
        log.info("参数" + transfer.toString());
        String token = request.getHeader("qz-Token");

        String outWarehouseId = (String) transfer.get("outWarehouseId");
        String saveWarehouseId = (String) transfer.get("saveWarehouseId");
        Boolean serialNumberStatus = (Boolean) transfer.get("serialNumberStatus");
        List<Map<String, String>> serialNumbers = (List<Map<String, String>>) transfer.get("serialNumbers"); // {serialNumbers:序列号， orderID:订单好}

        Boolean type = (Boolean) transfer.get("type");

        // 判断数据有消息
        if (outWarehouseId == null || saveWarehouseId == null || serialNumbers == null || serialNumberStatus == null || type == null)
            return Result.fail(Code.UPDATE_FAIL_CODE, "数据有误");

        // 库存调拨的序列号
        List<String> sNum = new ArrayList<>();


        for (Map<String, String> serialNumber : serialNumbers) {
            sNum.add(serialNumber.get("serialNumber"));
        }

        // 序列号调拨
        transferRecordService.TransferGoods(outWarehouseId, saveWarehouseId, sNum, token);

        // 订单
        if (type) {

            // 更新序列号状态
            for (Map<String, String> serialNumber : serialNumbers) {
                String sNumber = serialNumber.get("serialNumber");
                String orderId = serialNumber.get("orderId");

                if (orderId != null) {
                    LambdaQueryWrapper<OrderSerialNumber> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(OrderSerialNumber::getSerialNumber, sNumber);
                    wrapper.eq(OrderSerialNumber::getOrderId, orderId);
                    OrderSerialNumber one = serialNumberService.getOne(wrapper);
                    one.setStatus(serialNumberStatus);
                    serialNumberService.updateById(one);
                }
            }
        } else {
            // 收货
            // 更新序列号状态
            for (Map<String, String> serialNumber : serialNumbers) {
                String sNumber = serialNumber.get("serialNumber");
                String receiveGoodsId = serialNumber.get("receiveGoodsId");

                if (receiveGoodsId != null) {
                    LambdaQueryWrapper<GoodsSerialNumber> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(GoodsSerialNumber::getSerialNumber, sNumber);
                    wrapper.eq(GoodsSerialNumber::getReceiveGoodsId, receiveGoodsId);
                    GoodsSerialNumber one = goodsSerialNumberService.getOne(wrapper);
                    one.setStatus(serialNumberStatus);
                    goodsSerialNumberService.updateById(one); // 更新状态
                }
            }
        }


        return Result.success("调拨成功");
    }


    /**
     * 删除序列号
     */
    @DeleteMapping("/deleteById")
    public Result<?> deleteSerialNumber(@RequestBody OrderSerialNumber serialNumber, HttpServletRequest request) {

        serialNumberService.deleteExitLogs(serialNumber);

        // 更具序列号ID删除序列号
        serialNumberService.removeById(serialNumber.getId());

        // 查询订单订单ID

        String token = request.getHeader("qz-Token");

        User userinfoForBack = userService.getUserinfoForBack(token);

        // 添加日志
        orderLogService.AddSystemLog(serialNumber.getOrderId(), "删除序列号：" + serialNumber.getSerialNumber(), userinfoForBack.getUsername());


        return Result.success("删除序列号成功");
    }


    // 序列号出库
    @PostMapping("/updateSerialNumberStatus")
    public Result<?> updateSerialNumber(@RequestBody Map<String, Object> serialNumbersAndStatus) {
        // 更具序列号ID删除序列号
        String serialNumber = (String) serialNumbersAndStatus.get("serialNumber");
        Boolean status = (Boolean) serialNumbersAndStatus.get("status");
        Boolean type = (Boolean) serialNumbersAndStatus.get("type");


        if (serialNumber == null || status == null || type == null)
            return Result.fail(Code.UPDATE_FAIL_CODE, "数据格式有误");


        if (type) {
            // 订单
            // 查询序列号
            // 查询待出库的
            LambdaQueryWrapper<OrderSerialNumber> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderSerialNumber::getSerialNumber, serialNumber);
            wrapper.eq(OrderSerialNumber::getStatus, Code.DAI_CHU_KU);
            OrderSerialNumber one = serialNumberService.getOne(wrapper);

            if (one == null) return Result.fail(Code.UPDATE_FAIL_CODE, "序列号已出库");

            // 更新序列号状态
            one.setStatus(status);
            serialNumberService.updateById(one);

            // 删除序列号重复日志


        } else {
            // 收货
            LambdaQueryWrapper<GoodsSerialNumber> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GoodsSerialNumber::getSerialNumber, serialNumber);
            wrapper.eq(GoodsSerialNumber::getStatus, Code.DAI_RU_KU);
            GoodsSerialNumber one = goodsSerialNumberService.getOne(wrapper);

            if (one == null) return Result.fail(Code.UPDATE_FAIL_CODE, "序列号已入库");

            // 更新序列号状态
            one.setStatus(status);
            goodsSerialNumberService.updateById(one);
        }


        return Result.success("更新成功");
    }

}
